import {
  Args,
  Parent,
  ResolveProperty,
  Resolver,
  Query,
  Mutation,
  Subscription,
} from '@nestjs/graphql';

const pubSub = new PubSub();

@Resolver('Author')
export class AuthorResolver {
  constructor(
    private readonly authorsService: AuthorsService,
    private readonly postsService: PostsService,
  ) {}

  @Query('author')
  async getAuthor(@Args('id') id: number) {
    return await this.authorsService.findOneById(id);
  }

  @Mutation()
  async upvotePost(@Args('postId') postId: number) {
    return await this.postsService.upvoteById({ id: postId });
  }

  @ResolveProperty('posts')
  async getPosts(@Parent() author) {
    const { id } = author;
    return await this.postsService.findAll({ authorId: id });
  }

  @Subscription('commentAdded', {
    filter: (payload, variables) =>
      payload.commentAdded.repositoryName === variables.repoFullName,
    resolve: (value) => value,
  })
  commentAdded() {
    return pubSub.asyncIterator('commentAdded');
  }
}
